package org.practice.dao;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.practice.model.Category;
import org.practice.util.DaoException;
import org.springframework.stereotype.Repository;
@Repository(value="categoryDao")//默认单例模式，默认beanName="categoryDaoImpl"(类名首字母小写),ctx.getBean("categoryDao");
public class CategoryDaoImpl implements CategoryDao{
	private static Logger logger=Logger.getLogger(CategoryDaoImpl.class);
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Resource//默认beanName="sessionFactory",Spring根据name去上下文中查找bean,找到后注入进来,org.hibernate.impl.SessionImpl
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Category findCategoryById(Integer id) {
//		Session session=HibernateSessionFactory.openSession();
		Session session=sessionFactory.openSession();
		//标准手工进行事务控制,如果使用模板，则不用try..catch..finally
		Transaction tr=null;
		Category category=null;
		try {
			tr=session.beginTransaction();
//			category=(Category)session.createQuery("from Category c where c.id=?").setLong(0, id).uniqueResult();
			category=(Category)session.get(Category.class, id);
			if (category == null) {
				throw new DaoException("无法找到指定Id的分类");
			}
			tr.commit();
			session.close();
		} catch (HibernateException e) {
			tr.rollback();
			logger.error("数据访问出错！",e);
			throw new DaoException("数据访问出错",e);
		}
		return category;
	}

}
